package com.yao.sys.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.enums.SysErrorEnum;
import com.yao.common.exception.BusinessException;
import com.yao.home.CommonStatusEnum;
import com.yao.sys.entity.AccountEntity;
import com.yao.sys.entity.dto.AccountDto;
import com.yao.sys.entity.dto.UserDto;
import com.yao.sys.enums.SexEnum;
import com.yao.sys.mapper.AccountMapper;
import com.yao.sys.service.AccountService;
import com.yao.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 账户表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2019-12-09
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDto> implements AccountService {

    @Autowired
    private AccountMapper mapper;

    @Autowired
    private UserService userService;

    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public AccountDto add(AccountDto model) {
        AccountDto one = this.getOne(this.queryWrapper(model));

        if (null != one) {
            Console.error("新增失败,已经存在相同的手机号码:{}或账户名称:{}", model.getPhone(), model.getAccountName());
            throw new BusinessException(SysErrorEnum.ERROR, "手机号相同");
        }
        ;

        // MD5加密password
        String encryptPwd = SecureUtil.md5(model.getPassword());
        model.setPassword(encryptPwd);
        // 创建账号
        this.save(model);

        // 创建用户
        UserDto userDto = new UserDto();
        userDto.setAccountId(model.getId())
                .setStatus(CommonStatusEnum.VALID)
                .setUserName(model.getName()+ StrUtil.sub(UUID.fastUUID().toString(), 0 , 2))
                .setPassword(encryptPwd)
                .setSex(SexEnum.MALE.getCode())
                .setIdCard("")
                .setPhone(model.getPhone());

        userService.save(userDto);

        return model;
    }

    @Override
    public boolean modify(AccountDto model) {
        return this.updateById(model);
    }

    @Override
    public boolean deleteById(Integer id) {
        AccountEntity one = this.getById(id);
        if (null == one) {
            throw new BusinessException("不存在可被删除的数据.id = " + id);
        }

        // 删除关联的用户
        LambdaQueryWrapper<UserDto> query = Wrappers.lambdaQuery();
        query.eq(UserDto::getAccountId, id);
        List<UserDto> list = userService.list(query);
        list.forEach(dto -> userService.deleteById(dto.getId()));

        return this.removeById(id);
    }

    private LambdaQueryWrapper<AccountDto> queryWrapper(AccountDto model) {
        LambdaQueryWrapper<AccountDto> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StrUtil.isNotBlank(model.getPhone()), AccountEntity::getPhone, model.getPhone()).or()
            .eq(StrUtil.isNotBlank(model.getAccountName()), AccountEntity::getAccountName, model.getAccountName());

        return queryWrapper;
    }

    @Override
    public IPage<AccountDto> listpage(Page<AccountDto> page) {
        IPage<AccountDto> listpage = mapper.listpage(page);

        return listpage;
    }
}